package com.github.mvc.servlet;

import com.github.mvc.annotations.AutoWired;
import com.github.mvc.annotations.Controller;
import com.github.mvc.annotations.RequestMapping;
import com.github.mvc.annotations.Service;
import com.github.mvc.domain.Handler;
import com.github.mvc.utils.Resources;
import org.apache.commons.lang3.StringUtils;
import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;

import javax.servlet.ServletConfig;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.lang.reflect.Parameter;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Properties;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * 核心控制器
 *
 * @author ArchieSean
 * @create 2023/8/31
 */
public class MyDispatcherServlet extends HttpServlet {

    /**
     * 配置文件缓存
     */
    private Properties properties = new Properties();

    /**
     * 扫描到的类的全限定类名缓存
     */
    private List<String> classNames = new ArrayList<>();
    /**
     * 模拟ioc容器
     */
    private Map<String, Object> context = new HashMap<>(16);

    /**
     * 模拟 handlerMapping
     */
    private List<Handler> handlerMapping = new ArrayList<>();

    @Override
    public void init(ServletConfig config) throws ServletException {
        //加载配置文件，springmvc.xml
        String location = config.getInitParameter("contextConfigLocation");
        doLoadConfig(location);
        //扫描注解相关类
        doScan(properties.getProperty("scan-package"));
        // 初始化Bean对象
        try {
            initBean();
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
        // 实现依赖注入
        doAutoWired();
        // 初始化mvc的相关组件：handlerMapping，将配置好的url和method做映射处理
        initHandlerMapping();
        // 等待请求进入，处理请求。
        System.out.println("mini mvc 初始化完成.....");
    }

    /**
     * 构造HandlerMapping
     */
    private void initHandlerMapping() {
        if (context.isEmpty()) return;
        for (Map.Entry<String, Object> entry : context.entrySet()) {
            //获取ioc中对象的类型
            Class<?> aClass = entry.getValue().getClass();
            if (!aClass.isAnnotationPresent(Controller.class)) {
                continue;
            }
            String baseUrl = "";
            if (aClass.isAnnotationPresent(RequestMapping.class)) {
                RequestMapping annotation = aClass.getAnnotation(RequestMapping.class);
                // == /demo
                baseUrl = annotation.value();
            }
            baseUrl = baseUrl.startsWith("/") ? baseUrl : "/" + baseUrl;
            //处理方法
            Method[] methods = aClass.getMethods();
            for (int i = 0; i < methods.length; i++) {
                Method method = methods[i];
                if (!method.isAnnotationPresent(RequestMapping.class)) {
                    continue;
                }
                //有标注时
                RequestMapping annotation = method.getAnnotation(RequestMapping.class);
                String methodUrl = annotation.value(); //query
                methodUrl = methodUrl.startsWith("/") ? methodUrl : "/" + methodUrl;
                String url = baseUrl + methodUrl;

                //建立url和method之间的关系
                Handler handler = new Handler(method, entry.getValue(), Pattern.compile(url));
                //参数顺序处理
                Parameter[] parameters = method.getParameters();
                for (int j = 0; j < parameters.length; j++) {
                    Parameter parameter = parameters[j];
                    if (parameter.getType() == HttpServletRequest.class
                            || parameter.getType() == HttpServletResponse.class) {
                        //如果是请求对象或者响应对象，直接存类型名称
                        handler.getParamIndexMapping().put(parameter.getType().getSimpleName(), j);
                    } else {
                        //预计<name,0>
                        handler.getParamIndexMapping().put(parameter.getName(), j);
                    }
                }
                handlerMapping.add(handler);
            }
        }
    }

    /**
     * 属性注入
     */
    private void doAutoWired() {
        if (context.isEmpty()) return;
        //依赖注入处理
        //遍历ioc容器中所有对象，查看字段属性，是否有@autowired注解
        for (Map.Entry<String, Object> entry : context.entrySet()) {
            //获取实例对象属性
            Field[] files = entry.getValue().getClass().getDeclaredFields();
            //遍历字段
            for (Field field : files) {
                if (!field.isAnnotationPresent(AutoWired.class)) {
                    continue;
                }
                //开启暴力反射
                field.setAccessible(true);
                AutoWired annotation = field.getAnnotation(AutoWired.class);
                String beanId = annotation.value();
                //没有设置beanId时
                if ("".equals(beanId.trim())) {
                    //根据当前字段类型注入
                    beanId = field.getType().getName();
                }
                //开始赋值，从ioc容器中取出对应的bean
                try {
                    field.set(entry.getValue(), context.get(beanId));
                } catch (IllegalAccessException e) {
                    throw new RuntimeException(e);
                }
            }
        }
    }

    /**
     * 初始化bean
     */
    private void initBean() throws Exception {
        //基于全限定类名使用反射技术实现bean对象创建
        if (classNames.isEmpty()) return;
        for (int i = 0; i < classNames.size(); i++) {
            String className = classNames.get(i);
            //反射
            Class<?> aClass = Class.forName(className);
            //区分controller和service
            if (aClass.isAnnotationPresent(Controller.class)) {
                //保存到ioc容器
                String lowerFirst = lowerFirst(aClass.getSimpleName());
                Object instance = aClass.newInstance();
                context.put(lowerFirst, instance);
            } else if (aClass.isAnnotationPresent(Service.class)) {
                Service annotation = aClass.getAnnotation(Service.class);
                //获取bean名称
                String beanName = annotation.value();
                if (!"".equals(beanName.trim())) {
                    context.put(beanName, aClass.newInstance());
                } else {
                    String lowerFirst = lowerFirst(aClass.getSimpleName());
                    context.put(lowerFirst, aClass.newInstance());
                }
                //service 层接口
                Class<?>[] interfaces = aClass.getInterfaces();
                for (Class<?> anInterface : interfaces) {
                    //方便后续注入service实例对象
                    context.put(anInterface.getName(), aClass.newInstance());
                }
            } else {
                continue;
            }
        }
    }

    /**
     * 类名首字母小写转换方法
     *
     * @param str str
     * @return str
     */
    public String lowerFirst(String str) {
        char[] charArray = str.toCharArray();
        if ('A' <= charArray[0] && charArray[0] <= 'Z') {
            charArray[0] += 32;
        }
        return String.valueOf(charArray);
    }

    /**
     * 扫描类
     */
    private void doScan(String scanPackage) {
        //包在磁盘上的具体路径
        String scanPackagePath = Thread.currentThread().getContextClassLoader().getResource("").getPath()
                + scanPackage.replaceAll("\\.", "/");
        File pack = new File(scanPackagePath);
        File[] files = pack.listFiles();
        for (File file : files) {
            if (file.isDirectory()) {
                //子包，递归
                doScan(scanPackage + "." + file.getName());
            } else if (file.getName().endsWith("class")) {
                String className = scanPackage + "." + file.getName().replaceAll(".class", "");
                classNames.add(className);
            }
        }
    }

    /**
     * 加载配置文件
     *
     * @param location 配置文件路径
     */
    private void doLoadConfig(String location) {
        //获取springmvc.xml的输入流
        InputStream inputStream = Resources.getResourceAsStream(location);
        //开始解析xml文件内容
        Document document = null;
        try {
            document = new SAXReader().read(inputStream);
        } catch (DocumentException e) {
            throw new RuntimeException(e);
        }
        //获取根标签
        Element rootElement = document.getRootElement();
        //获取包扫描路径
        List<Element> list = rootElement.selectNodes("//scan-package");
        //此处包扫描标签唯一
        if (list.size() == 1) {
            Element element = list.get(BigDecimal.ZERO.intValue());
            //封装包扫描到properties
            String basePackage = element.attributeValue("base-package");
            properties.put("scan-package", basePackage);
        }
    }

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        doPost(req, resp);
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        //获取请求url，找到对应method去调用
        Handler handler = getHandler(req);
        if (null == handler) {
            resp.getWriter().write("404 not found");
            return;
        }
        //参数绑定
        //获取所有参数类型数组，这个数组的长度就是最后要传入的args的长度
        Class<?>[] parameterTypes = handler.getMethod().getParameterTypes();
        //根据上边的长度创建一个新数组
        Object[] paraValues = new Object[parameterTypes.length];
        //参数塞值，需要保证参数顺序一致
        Map<String, String[]> parameterMap = req.getParameterMap();
        //遍历request中的参数
        for (Map.Entry<String, String[]> param : parameterMap.entrySet()) {
            // 如同 1,2
            String value = StringUtils.join(param.getValue(), ",");
            //填充数据
            if (!handler.getParamIndexMapping().containsKey(param.getKey())) {
                continue;
            }
            //存在对应参数，找到其对应索引位置
            Integer index = handler.getParamIndexMapping().get(param.getKey());

            //存值{将前端传过来的数据存到对应位置}
            paraValues[index] = value;
        }
        List<?> list = Arrays.asList(parameterTypes);
        //目标方法包含请求和响应对象时
        if (list.contains(HttpServletRequest.class)
                || list.contains(HttpServletResponse.class)) {
            //处理参数中存在请求对象或者响应对象问题
            int reqIndex = handler.getParamIndexMapping().get(HttpServletRequest.class.getSimpleName());
            paraValues[reqIndex] = req;
            int respIndex = handler.getParamIndexMapping().get(HttpServletResponse.class.getSimpleName());
            paraValues[respIndex] = resp;
        }
        //执行方法
        try {
            Object invoke = handler.getMethod().invoke(handler.getController(), paraValues);
            if (null != invoke) {
                resp.getWriter().write(invoke.toString());
            }
        } catch (IllegalAccessException e) {
            throw new RuntimeException(e);
        } catch (InvocationTargetException e) {
            throw new RuntimeException(e);
        }
    }

    /**
     * 获取对应的handler
     *
     * @param req req
     * @return handler
     */
    private Handler getHandler(HttpServletRequest req) {
        if (handlerMapping.isEmpty()) return null;
        String uri = req.getRequestURI();
        for (Handler handler : handlerMapping) {
            Matcher matcher = handler.getPattern().matcher(uri);
            if (!matcher.matches()) continue;
            return handler;
        }
        return null;
    }

}
